Auto-Suggest Dropdown in Selenium WebDriver
An Auto-Suggest Dropdown, also called an Autocomplete Dropdown, is a dynamic web component that displays a list of suggestions while the user types text into an input field. The suggestions may be generated from local data, JavaScript logic, an API, AJAX requests, or a server-side search.
Auto-suggest dropdowns are commonly used in search boxes, country selection, city selection, flight booking applications, hotel booking applications, e-commerce websites, address fields, employee search fields, customer selection fields, and many other modern web applications.
In Selenium WebDriver automation, an auto-suggest dropdown is usually handled differently from a normal HTML dropdown because its suggestions are often created dynamically after the user enters text.
Important: Selenium's Select class is intended for actual HTML <select> elements and their <option> elements. Custom dropdowns built using elements such as div, ul, and li need normal WebElement interactions instead. Selenium Select Documentation
Selenium Training Course | Register for Course Demo
1. What is an Auto-Suggest Dropdown?
An Auto-Suggest Dropdown is a user-interface component that automatically displays possible matching values as the user types into an input field.
For example, when the user enters Ind in a country search field, the application may display:
- India
- Indonesia
- Indiana
- Indore
The user can then select the required suggestion from the dynamically displayed list.
2. Simple Auto-Suggest Example
<input type="text" id="country" placeholder="Search country">
<ul class="suggestions">
<li>India</li>
<li>Indonesia</li>
<li>Iceland</li>
</ul>
3. How Auto-Suggest Works
User enters text
↓
Input event is triggered
↓
Application processes the text
↓
API / AJAX / local filtering
↓
Matching results are generated
↓
DOM is updated
↓
Suggestions become visible
↓
User selects a suggestion
4. Why Auto-Suggest Dropdowns Are Important in Selenium
Auto-suggest dropdowns are important in Selenium because modern web applications frequently use dynamic UI components instead of traditional HTML controls. The suggestion elements may not exist when the page initially loads and may be inserted or replaced after typing.
Therefore, automation needs proper element identification, synchronization, dynamic element handling, and verification.
5. Auto-Suggest Dropdown vs Normal Dropdown
| Feature | Normal HTML Dropdown | Auto-Suggest Dropdown |
| Typical HTML | <select> | input, div, ul, li |
| Options | Usually represented by <option> | Often dynamically generated |
| Selection | Select an option | Type and select suggestion |
| Select class | Supported | Generally not applicable |
| AJAX/API | Usually unnecessary | Frequently used |
| Waiting | Often simpler | Usually requires synchronization |
| Dynamic DOM | Less common | Very common |
6. Important Rule About Selenium Select
The Selenium Select class should be used only when the target element is an HTML <select>. Selenium documentation explicitly states that the Select class works with select and option elements and does not work with JavaScript dropdowns created using elements such as div or li.
WebElement element =
driver.findElement(By.id("country"));
Select select = new Select(element);
The above code is appropriate only when country identifies a real <select> element.
7. Basic Auto-Suggest HTML Structure
<div class="search-container">
<input
id="country"
type="text"
placeholder="Search country">
<ul class="suggestions">
<li>India</li>
<li>Indonesia</li>
<li>Iceland</li>
</ul>
</div>
8. Basic Selenium Automation Flow
Open application
↓
Locate input field
↓
Click input if required
↓
Enter search text
↓
Wait for suggestions
↓
Locate required suggestion
↓
Click suggestion
↓
Verify selected value
9. Basic Java Selenium Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class AutoSuggestExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
WebElement input =
driver.findElement(By.id("country"));
input.sendKeys("Ind");
WebElement option =
driver.findElement(
By.xpath("//li[normalize-space()='India']")
);
option.click();
} finally {
driver.quit();
}
}
}
10. Locating the Input Field
The first step in automating an auto-suggest dropdown is to locate the input element where the user enters the search text.
WebElement input =
driver.findElement(By.id("country"));
11. Using ID Locator
WebElement input =
driver.findElement(By.id("country"));
input.sendKeys("Ind");
12. Using Name Locator
WebElement input =
driver.findElement(By.name("country"));
input.sendKeys("Ind");
13. Using CSS Selector
WebElement input =
driver.findElement(
By.cssSelector("input#country")
);
input.sendKeys("Ind");
14. Using XPath
WebElement input =
driver.findElement(
By.xpath("//input[@id='country']")
);
input.sendKeys("Ind");
15. Using Placeholder Attribute
WebElement input =
driver.findElement(
By.xpath("//input[@placeholder='Search country']")
);
input.sendKeys("Ind");
16. Entering Search Text
Once the input is located, use sendKeys() to enter the text that should generate suggestions.
input.sendKeys("Ind");
17. Clearing Existing Text
input.clear();
input.sendKeys("India");
18. Replacing Existing Text
input.click();
input.sendKeys(Keys.CONTROL, "a");
input.sendKeys("Mumbai");
19. Importing Keys
import org.openqa.selenium.Keys;
20. Why Suggestions Are Dynamic
Auto-suggest results may be generated only after the application receives the text entered by the user. JavaScript may then filter local data or send a request to a backend service.
Enter "Ind"
↓
JavaScript event
↓
Search/filter operation
↓
Results generated
↓
DOM updated
↓
Suggestions displayed
21. Dynamic DOM
A major challenge with auto-suggest controls is that suggestion elements can be dynamically inserted, removed, or replaced.
For example, the following elements might not exist when the page first loads:
<li>India</li>
<li>Indonesia</li>
<li>Indore</li>
22. Why Explicit Wait Is Important
Because suggestions may appear after JavaScript or an API operation completes, Selenium should wait for the required condition instead of assuming that the suggestion is immediately available.
Selenium's waiting documentation explains that dynamic web applications can change the DOM after the browser has returned control to the test code. Explicit waits allow a test to wait for a specific condition. Selenium Expected Conditions
23. Creating WebDriverWait
import java.time.Duration;
import org.openqa.selenium.support.ui.WebDriverWait;
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
24. Waiting for Suggestion Visibility
WebElement option = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//li[normalize-space()='India']")
)
);
25. Importing ExpectedConditions
import org.openqa.selenium.support.ui.ExpectedConditions;
26. Waiting for Clickability
WebElement option = wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath("//li[normalize-space()='India']")
)
);
option.click();
27. Complete Example with Explicit Wait
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AutoSuggestWaitExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement input =
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
By.id("country")
)
);
input.sendKeys("Ind");
WebElement option =
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[normalize-space()='India']"
)
)
);
option.click();
} finally {
driver.quit();
}
}
}
28. Selecting by Exact Visible Text
driver.findElement(
By.xpath("//li[normalize-space()='India']")
).click();
29. Why normalize-space() Is Useful
normalize-space() helps when the displayed text contains leading, trailing, or inconsistent whitespace.
By.xpath("//li[normalize-space()='India']")
30. Using contains() in XPath
When exact text is not stable, contains() can be used carefully.
By.xpath(
"//li[contains(normalize-space(),'India')]"
)
31. Exact Text vs Partial Text
| Method | Example | Use |
| Exact | normalize-space()='India' | When text is stable |
| Partial | contains(normalize-space(),'India') | When text may contain additional information |
32. Selecting the First Suggestion
WebElement firstOption =
driver.findElement(
By.cssSelector(".suggestions li")
);
firstOption.click();
Selecting the first suggestion should be used only when the application's intended behavior requires the first result.
33. Finding All Suggestions
List<WebElement> suggestions =
driver.findElements(
By.cssSelector(".suggestions li")
);
34. Importing List
import java.util.List;
35. Printing All Suggestions
List<WebElement> suggestions =
driver.findElements(
By.cssSelector(".suggestions li")
);
for (WebElement suggestion : suggestions) {
System.out.println(
suggestion.getText()
);
}
36. Selecting a Specific Suggestion
String expected = "India";
List<WebElement> suggestions =
driver.findElements(
By.cssSelector(".suggestions li")
);
for (WebElement suggestion : suggestions) {
if (suggestion.getText()
.trim()
.equals(expected)) {
suggestion.click();
break;
}
}
37. Case-Insensitive Selection
String expected = "india";
for (WebElement suggestion : suggestions) {
String actual =
suggestion.getText().trim();
if (actual.equalsIgnoreCase(expected)) {
suggestion.click();
break;
}
}
38. Handling Extra Spaces
String actual =
suggestion.getText().trim();
if (actual.equalsIgnoreCase("India")) {
suggestion.click();
}
39. Locating Suggestions with CSS
List<WebElement> suggestions =
driver.findElements(
By.cssSelector(".suggestions li")
);
40. Locating Suggestions with XPath
List<WebElement> suggestions =
driver.findElements(
By.xpath(
"//ul[contains(@class,'suggestions')]/li"
)
);
41. Using Data Attributes
Custom data attributes can provide stable locators when available.
WebElement option =
driver.findElement(
By.cssSelector("[data-value='India']")
);
option.click();
42. Dynamic IDs
Some applications generate dynamic IDs such as:
suggestion-101
suggestion-204
suggestion-309
Depending directly on the changing number can make tests fragile.
43. CSS Starts-With Selector
By.cssSelector("[id^='suggestion-']")
44. XPath starts-with()
By.xpath(
"//*[starts-with(@id,'suggestion-')]"
)
45. XPath contains() for Dynamic IDs
By.xpath(
"//*[contains(@id,'suggestion-')]"
)
46. Searchable Product Auto-Suggest
WebElement search =
driver.findElement(
By.id("productSearch")
);
search.sendKeys("Laptop");
WebElement product =
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[normalize-space()='Laptop Pro']"
)
)
);
product.click();
47. City Auto-Suggest
WebElement city =
driver.findElement(By.id("city"));
city.sendKeys("Mum");
wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath(
"//li[normalize-space()='Mumbai']"
)
)
).click();
48. Country Auto-Suggest
WebElement country =
driver.findElement(By.id("country"));
country.sendKeys("Ind");
wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath(
"//li[normalize-space()='India']"
)
)
).click();
49. Airport Auto-Suggest
WebElement departure =
driver.findElement(By.id("departure"));
departure.sendKeys("Del");
wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath(
"//li[contains(normalize-space(),'Delhi')]"
)
)
).click();
50. Address Auto-Complete
WebElement address =
driver.findElement(By.id("address"));
address.sendKeys("Mumbai");
wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath(
"//li[contains(normalize-space(),'Mumbai')]"
)
)
).click();
51. Google-Like Search Suggestions
WebElement search =
driver.findElement(By.name("q"));
search.sendKeys("Selenium");
List<WebElement> suggestions =
wait.until(
ExpectedConditions
.visibilityOfAllElementsLocatedBy(
By.cssSelector(".suggestion")
)
);
for (WebElement suggestion : suggestions) {
if (suggestion.getText()
.contains("Selenium WebDriver")) {
suggestion.click();
break;
}
}
52. Waiting for Multiple Suggestions
List<WebElement> suggestions =
wait.until(
ExpectedConditions
.visibilityOfAllElementsLocatedBy(
By.cssSelector(".suggestions li")
)
);
53. Presence vs Visibility
| Condition | Meaning | Use |
| Presence | Element exists in DOM | DOM-level checks |
| Visibility | Element exists and is visible | Visible suggestions |
| Clickable | Element is visible and enabled | Before clicking |
| Staleness | Element is no longer attached | After dynamic refresh |
54. Presence of Suggestion
WebElement suggestion =
wait.until(
ExpectedConditions
.presenceOfElementLocated(
By.cssSelector(".suggestions li")
)
);
55. Visibility of Suggestion
WebElement suggestion =
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
By.cssSelector(".suggestions li")
)
);
56. Clickability of Suggestion
WebElement suggestion =
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[normalize-space()='India']"
)
)
);
suggestion.click();
57. Why Thread.sleep() Should Not Be the Main Strategy
A fixed delay waits for a predetermined amount of time whether the suggestion is ready or not. Condition-based waits allow the test to proceed when the required state is reached.
Thread.sleep(3000);
For dynamic auto-suggest controls, an explicit wait is generally more precise.
58. AJAX-Based Auto-Suggest
Some auto-suggest components send a request to a server after text is entered.
Enter search text
↓
AJAX/API request
↓
Server response
↓
JavaScript processes response
↓
Suggestion list updated
↓
Required option becomes available
59. Waiting for AJAX Suggestions
input.sendKeys("Ind");
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
By.cssSelector(".suggestions")
)
);
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[normalize-space()='India']"
)
)
).click();
60. StaleElementReferenceException
A stale element problem can occur when the application replaces the suggestion element after the test has already located it.
WebElement option =
driver.findElement(
By.cssSelector(".suggestions li")
);
input.clear();
input.sendKeys("Ind");
The old reference may no longer represent the current DOM element after the suggestion list refreshes.
61. Re-Locating After Refresh
WebElement currentOption =
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[normalize-space()='India']"
)
)
);
currentOption.click();
62. Waiting for Staleness
WebElement oldElement =
driver.findElement(
By.cssSelector(".suggestions li")
);
input.clear();
input.sendKeys("Ind");
wait.until(
ExpectedConditions.stalenessOf(
oldElement
)
);
63. NoSuchElementException
NoSuchElementException can occur when Selenium cannot locate the requested suggestion.
Possible reasons include:
- Incorrect locator
- Suggestion has not loaded
- Wrong suggestion text
- Incorrect frame
- DOM changed
- Suggestion disappeared
64. TimeoutException
A TimeoutException can occur when the expected condition is not satisfied within the specified timeout.
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
65. ElementClickInterceptedException
This can occur when another element or overlay prevents Selenium from clicking the suggestion.
Possible solutions include:
- Wait for the correct element state.
- Wait for an overlay to disappear.
- Scroll the element into view when appropriate.
- Inspect overlapping elements.
- Use JavaScript only as a controlled fallback.
66. Keyboard Navigation
Some auto-suggest components support keyboard navigation.
input.sendKeys("Ind");
input.sendKeys(Keys.ARROW_DOWN);
input.sendKeys(Keys.ENTER);
67. Selecting the Highlighted Suggestion
input.sendKeys("Mumbai");
input.sendKeys(Keys.ARROW_DOWN);
input.sendKeys(Keys.ENTER);
This technique should be used only when the application's autocomplete widget supports keyboard navigation.
68. Multiple Auto-Suggest Fields
A form may contain several autocomplete fields, such as:
- Departure city
- Destination city
- Country
- Product
- Customer
- Employee
- Address
69. Departure and Destination Example
WebElement from =
driver.findElement(By.id("from"));
from.sendKeys("Delhi");
wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath(
"//li[normalize-space()='Delhi']"
)
)
).click();
WebElement to =
driver.findElement(By.id("to"));
to.sendKeys("Mumbai");
wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath(
"//li[normalize-space()='Mumbai']"
)
)
).click();
70. Dependent Auto-Suggest Fields
Some fields depend on previous selections.
Select Country
↓
City field becomes active
↓
Enter City
↓
City suggestions generated
↓
Select City
71. Dependent Dropdown Example
country.sendKeys("India");
wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath(
"//li[normalize-space()='India']"
)
)
).click();
city.sendKeys("Mumbai");
wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath(
"//li[normalize-space()='Mumbai']"
)
)
).click();
72. Auto-Suggest with Nested Elements
Suggestions may contain multiple child elements.
<li class="suggestion">
<span class="city">Mumbai</span>
<span class="country">India</span>
</li>
73. Locating Nested Suggestion
WebElement option =
driver.findElement(
By.xpath(
"//li[.//span[normalize-space()='Mumbai']]"
)
);
option.click();
74. Selecting by City and Country
WebElement option =
driver.findElement(
By.xpath(
"//li[.//span[normalize-space()='Mumbai']" +
" and .//span[normalize-space()='India']]"
)
);
option.click();
75. Getting Suggestion Text
String text =
option.getText();
System.out.println(text);
76. Verifying the Selected Value
After selecting the suggestion, verify the value present in the input field.
String actualValue =
input.getAttribute("value");
System.out.println(actualValue);
77. TestNG Assertion
import static org.testng.Assert.assertEquals;
String actual =
input.getAttribute("value");
assertEquals(
actual,
"India"
);
78. Using assertTrue()
import static org.testng.Assert.assertTrue;
assertTrue(
input.getAttribute("value")
.contains("India")
);
79. Verifying Suggestion Count
List<WebElement> suggestions =
driver.findElements(
By.cssSelector(".suggestions li")
);
assertTrue(
suggestions.size() > 0
);
80. Verifying a Specific Suggestion Exists
boolean found = false;
for (WebElement suggestion : suggestions) {
if (suggestion.getText()
.trim()
.equalsIgnoreCase("India")) {
found = true;
break;
}
}
assertTrue(found);
81. Verifying Suggestion Container
WebElement container =
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
By.cssSelector(".suggestions")
)
);
assertTrue(
container.isDisplayed()
);
82. ARIA Attributes in Auto-Suggest
Modern accessible autocomplete components may use ARIA attributes such as:
role="combobox"
role="listbox"
role="option"
aria-expanded
aria-controls
aria-activedescendant
83. Locating an Option by ARIA Role
WebElement option =
driver.findElement(
By.cssSelector("[role='option']")
);
84. Locating a Specific ARIA Option
WebElement option =
driver.findElement(
By.xpath(
"//*[@role='option' and " +
"normalize-space()='India']"
)
);
85. Checking aria-expanded
String expanded =
input.getAttribute(
"aria-expanded"
);
System.out.println(expanded);
86. Verifying the Dropdown Is Open
String expanded =
input.getAttribute(
"aria-expanded"
);
assertEquals(
expanded,
"true"
);
87. Auto-Suggest Inside an iframe
If the autocomplete component is inside an iframe, Selenium must switch to the iframe before interacting with its elements.
driver.switchTo().frame(
driver.findElement(
By.id("searchFrame")
)
);
WebElement search =
driver.findElement(
By.id("city")
);
search.sendKeys("Mumbai");
driver.findElement(
By.xpath(
"//li[normalize-space()='Mumbai']"
)
).click();
driver.switchTo().defaultContent();
88. Why iframe Handling Is Required
An iframe represents a separate browsing context. Selenium must switch into that context before locating elements inside it.
89. Auto-Suggest Inside Shadow DOM
Modern applications can use Shadow DOM to implement custom components. Selenium 4 provides APIs for accessing a shadow root.
WebElement host =
driver.findElement(
By.cssSelector("search-component")
);
SearchContext shadowRoot =
host.getShadowRoot();
WebElement input =
shadowRoot.findElement(
By.cssSelector("input")
);
input.sendKeys("India");
90. Selecting Shadow DOM Suggestion
WebElement option =
shadowRoot.findElement(
By.cssSelector(".suggestion")
);
option.click();
91. Page Object Model for Auto-Suggest
In a Page Object Model framework, auto-suggest functionality can be encapsulated inside page classes so that test cases remain clean and reusable.
public class SearchPage {
private WebDriver driver;
private WebDriverWait wait;
private By searchBox =
By.id("search");
private By suggestions =
By.cssSelector(".suggestions li");
public SearchPage(WebDriver driver) {
this.driver = driver;
this.wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
}
public void searchAndSelect(
String searchText,
String expectedText) {
WebElement input =
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
searchBox
)
);
input.clear();
input.sendKeys(searchText);
List<WebElement> options =
wait.until(
ExpectedConditions
.visibilityOfAllElementsLocatedBy(
suggestions
)
);
for (WebElement option : options) {
if (option.getText()
.trim()
.equalsIgnoreCase(
expectedText
)) {
option.click();
break;
}
}
}
}
92. Calling Page Object Method
SearchPage searchPage =
new SearchPage(driver);
searchPage.searchAndSelect(
"Ind",
"India"
);
93. Reusable Utility Method
public static void selectSuggestion(
WebDriver driver,
WebDriverWait wait,
By inputLocator,
String searchText,
By suggestionLocator) {
WebElement input =
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
inputLocator
)
);
input.clear();
input.sendKeys(searchText);
WebElement suggestion =
wait.until(
ExpectedConditions
.elementToBeClickable(
suggestionLocator
)
);
suggestion.click();
}
94. Calling the Utility Method
selectSuggestion(
driver,
wait,
By.id("country"),
"Ind",
By.xpath(
"//li[normalize-space()='India']"
)
);
95. Generic Text-Based Utility
public static void selectSuggestionByText(
WebDriver driver,
WebDriverWait wait,
By inputLocator,
String searchText,
String expectedText) {
WebElement input =
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
inputLocator
)
);
input.clear();
input.sendKeys(searchText);
By optionLocator =
By.xpath(
"//*[normalize-space()='" +
expectedText +
"']"
);
wait.until(
ExpectedConditions
.elementToBeClickable(
optionLocator
)
).click();
}
96. Common Locator Strategies
| Locator | Example | Use |
| ID | By.id("country") | Stable input field |
| CSS | By.cssSelector(".suggestions li") | Multiple suggestions |
| XPath text | By.xpath("//li[normalize-space()='India']") | Specific text |
| Data attribute | By.cssSelector("[data-value='India']") | Stable custom attribute |
| ARIA | By.cssSelector("[role='option']") | Accessible components |
97. Locator Priority
- Stable unique ID
- Stable data attribute
- Meaningful CSS selector
- Stable relative XPath
- ARIA attributes when appropriate
- Visible text when stable
98. Common Mistake: Using Select
Incorrect for a custom auto-suggest:
WebElement element =
driver.findElement(
By.id("country")
);
Select select =
new Select(element);
If the element is an input, div, or another non-select element, use normal WebElement interaction instead.
99. Common Mistake: Clicking Immediately
Incorrect:
input.sendKeys("Ind");
driver.findElement(
By.xpath(
"//li[normalize-space()='India']"
)
).click();
The suggestion may not have been rendered yet.
100. Better Approach
input.sendKeys("Ind");
WebElement india =
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[normalize-space()='India']"
)
)
);
india.click();
101. Common Mistake: Absolute XPath
/html/body/div[2]/div[1]/ul/li[3]
Absolute XPath can be fragile because DOM changes can alter the complete path.
102. Better Relative XPath
//ul[contains(@class,'suggestions')]//li[
normalize-space()='India'
]
103. Common Mistake: Generic li Locator
Using only:
By.tagName("li")
may return unrelated list items elsewhere on the page.
104. Better Scoped Locator
By.cssSelector(
".country-suggestions li"
)
105. Common Mistake: Overusing JavaScript
JavaScript can be used as a fallback for special cases, but normal Selenium interactions should generally be preferred.
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].click();",
option
);
106. When JavaScript May Be Used
- A known UI layer prevents normal interaction.
- A controlled fallback is required.
- The application has an unusual interaction mechanism.
- Debugging requires direct DOM interaction.
107. Handling Suggestions That Disappear
Some autocomplete lists disappear when the input loses focus. Therefore, avoid unnecessary interactions between typing and selecting the result.
input.sendKeys("India");
WebElement option =
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[normalize-space()='India']"
)
)
);
option.click();
108. Handling Frequently Refreshed Suggestions
input.sendKeys("Ind");
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
By.cssSelector(".suggestions")
)
);
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[normalize-space()='India']"
)
)
).click();
109. Negative Testing
Negative testing checks how the application behaves when no matching suggestion exists.
Enter invalid search
↓
Application searches
↓
No matching result
↓
"No results" message
↓
Verify expected behavior
110. No Results Example
input.sendKeys("XYZ123");
WebElement message =
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
By.cssSelector(".no-results")
)
);
assertTrue(
message.getText()
.contains("No results")
);
111. Empty Input Test
input.clear();
List<WebElement> suggestions =
driver.findElements(
By.cssSelector(".suggestions li")
);
assertTrue(
suggestions.isEmpty()
);
112. Special Character Test
input.sendKeys("@#$%");
Verify that the application handles special characters according to the expected requirements.
113. Long Search Text
input.sendKeys(
"ThisIsAVeryLongSearchValueForTesting"
);
114. Rapid Typing Test
Rapid typing can cause the suggestion list to change several times. The test should verify that the final suggestion corresponds to the final input value.
input.sendKeys("I");
input.sendKeys("n");
input.sendKeys("d");
115. Clear and Search Again
input.clear();
input.sendKeys("India");
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[normalize-space()='India']"
)
)
).click();
116. Disabled Suggestions
Some applications may display suggestions that cannot be selected. The test should check whether the element is enabled or whether the application marks it as unavailable.
if (option.isEnabled()) {
option.click();
}
117. Verifying Suggestion Is Displayed
assertTrue(
option.isDisplayed()
);
118. Verifying Suggestion Is Enabled
assertTrue(
option.isEnabled()
);
119. Complete Real-World Example
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CountryAutoSuggestTest {
public static void main(String[] args) {
WebDriver driver =
new ChromeDriver();
try {
driver.manage()
.window()
.maximize();
driver.get(
"https://example.com"
);
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement country =
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
By.id("country")
)
);
country.clear();
country.sendKeys("Ind");
List<WebElement> suggestions =
wait.until(
ExpectedConditions
.visibilityOfAllElementsLocatedBy(
By.cssSelector(
".suggestions li"
)
)
);
boolean selected = false;
for (WebElement suggestion :
suggestions) {
String text =
suggestion
.getText()
.trim();
System.out.println(
"Suggestion: " + text
);
if (text.equalsIgnoreCase(
"India")) {
suggestion.click();
selected = true;
break;
}
}
if (!selected) {
throw new RuntimeException(
"Required suggestion not found"
);
}
String selectedValue =
country.getAttribute("value");
System.out.println(
"Selected: " +
selectedValue
);
} finally {
driver.quit();
}
}
}
120. Complete Automation Flow
Launch Browser
↓
Open Application
↓
Locate Auto-Suggest Input
↓
Enter Search Text
↓
Wait for Suggestion Container
↓
Retrieve Suggestions
↓
Compare Suggestion Text
↓
Find Required Suggestion
↓
Click Suggestion
↓
Read Input Value
↓
Verify Selected Value
↓
Close Browser
121. Mini Project: Flight Booking Auto-Suggest
Create a Selenium automation project for a flight booking application containing departure and destination auto-suggest fields.
Requirements:
- Open the flight booking website.
- Locate the departure field.
- Enter the departure city.
- Wait for suggestions.
- Select the required departure location.
- Locate the destination field.
- Enter the destination city.
- Wait for suggestions.
- Select the required destination.
- Verify both selected values.
122. Flight Booking Flow
Flight Booking Page
↓
Departure Field
↓
Enter "Delhi"
↓
Wait for Suggestions
↓
Select "Delhi"
↓
Destination Field
↓
Enter "Mumbai"
↓
Wait for Suggestions
↓
Select "Mumbai"
↓
Verify Both Fields
123. Reusable Flight Location Method
public void selectLocation(
By inputLocator,
String searchText,
String expectedLocation) {
WebElement input =
wait.until(
ExpectedConditions
.visibilityOfElementLocated(
inputLocator
)
);
input.clear();
input.sendKeys(searchText);
By optionLocator =
By.xpath(
"//li[normalize-space()='" +
expectedLocation +
"']"
);
wait.until(
ExpectedConditions
.elementToBeClickable(
optionLocator
)
).click();
}
124. E-Commerce Product Search Example
WebElement search =
driver.findElement(
By.id("productSearch")
);
search.clear();
search.sendKeys("Laptop");
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[contains(normalize-space(),'Laptop')]"
)
)
).click();
125. Employee Search Example
WebElement employee =
driver.findElement(
By.id("employee")
);
employee.sendKeys("Rahul");
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[normalize-space()='Rahul Sharma']"
)
)
).click();
126. Customer Search Example
WebElement customer =
driver.findElement(
By.id("customer")
);
customer.sendKeys("Amit");
wait.until(
ExpectedConditions
.elementToBeClickable(
By.xpath(
"//li[contains(normalize-space(),'Amit')]"
)
)
).click();
127. Address Search Example
WebElement address =
driver.findElement(
By.id("address")
);
address.sendKeys(
"Mumbai Maharashtra"
);
wait.until(
ExpectedConditions
.elementToBeClickable(
By.cssSelector(
".address-suggestion"
)
)
).click();
128. Interview Question: What Is an Auto-Suggest Dropdown?
An Auto-Suggest Dropdown is a dynamic UI component that displays matching suggestions while the user types into an input field.
129. Interview Question: Can We Use Select for Auto-Suggest?
Normally no. The Selenium Select class is designed for HTML <select> elements. Custom autocomplete components using input, div, ul, or li should generally be handled using normal Selenium element interactions.
130. Interview Question: Why Is Explicit Wait Required?
Suggestions can be generated asynchronously after typing. Explicit waits allow the test to wait for a specific condition, such as the suggestion becoming visible or clickable.
131. Interview Question: How Do You Select a Specific Suggestion?
List<WebElement> options =
driver.findElements(
By.cssSelector(
".suggestions li"
)
);
for (WebElement option : options) {
if (option.getText()
.trim()
.equalsIgnoreCase(
"India"
)) {
option.click();
break;
}
}
132. Interview Question: How Do You Handle Dynamic IDs?
Use stable attributes, data attributes, meaningful classes, ARIA attributes, or relative XPath/CSS patterns instead of depending on changing portions of generated IDs.
133. Interview Question: How Do You Handle Stale Elements?
If JavaScript replaces the suggestion list, previously located elements may become stale. Re-locate the current element after the DOM update and use an appropriate wait.
134. Interview Question: How Do You Verify the Selection?
String value =
input.getAttribute("value");
assertEquals(
value,
"India"
);
135. Interview Question: How Do You Handle Auto-Suggest Inside an iframe?
driver.switchTo().frame(
frameElement
);
// interact with auto-suggest
driver.switchTo().defaultContent();
136. Interview Question: How Do You Handle Auto-Suggest Inside Shadow DOM?
WebElement host =
driver.findElement(
By.cssSelector(
"search-component"
)
);
SearchContext shadowRoot =
host.getShadowRoot();
WebElement input =
shadowRoot.findElement(
By.cssSelector("input")
);
137. Interview Question: What If Suggestions Change While Typing?
After the final search text is entered, wait for the current suggestion state and locate the required suggestion. If the DOM is replaced, use a fresh element lookup instead of an old WebElement reference.
138. Interview Question: How Can Keyboard Navigation Be Automated?
input.sendKeys("Ind");
input.sendKeys(Keys.ARROW_DOWN);
input.sendKeys(Keys.ENTER);
139. Best Practices
- Inspect the DOM before creating locators.
- Determine whether the component is native or custom.
- Do not use
Select for custom auto-suggest controls.
- Use stable locators.
- Use explicit waits for dynamic suggestions.
- Scope suggestion locators to the correct component.
- Use
normalize-space() where appropriate.
- Re-locate elements after dynamic DOM updates.
- Verify the final selected value.
- Use Page Object Model in larger frameworks.
- Use JavaScript only when a controlled fallback is actually required.
- Test positive and negative scenarios.
- Handle iframe and Shadow DOM scenarios correctly.
140. Common Problems and Solutions
| Problem | Possible Cause | Solution |
| Suggestion not found | Suggestion not loaded | Use explicit wait |
| Click fails | Overlay or wrong state | Wait for clickability |
| Stale element | DOM refreshed | Locate element again |
| Select exception | Element is not a select | Use WebElement interaction |
| Wrong suggestion selected | Generic locator | Use scoped locator |
| Dynamic ID | Generated identifier | Use stable attributes |
| Suggestions disappear | Input loses focus | Select immediately after waiting |
| Iframe element not found | Wrong browsing context | Switch to iframe |
| Shadow element not found | Shadow boundary | Access shadow root |
141. Testing Scenarios
- Enter valid search text.
- Enter partial search text.
- Enter invalid search text.
- Verify suggestions appear.
- Verify suggestion count.
- Select a specific suggestion.
- Select the first suggestion.
- Verify the selected value.
- Test keyboard navigation.
- Test no-result behavior.
- Test duplicate suggestions.
- Test dynamic loading.
- Test rapidly changing input.
- Test clearing and re-entering text.
- Test special characters.
- Test long input.
142. Auto-Suggest Automation Formula
Locate Input
+
Enter Search Text
+
Wait for Suggestions
+
Locate Required Option
+
Click Option
+
Verify Selected Value
=
Reliable Auto-Suggest Automation
143. Quick Revision
| Topic | Key Point |
| Auto-Suggest | Dynamic list generated from user input |
| Input | Enter search text |
| Suggestion | Dynamic matching result |
| Select | Use only for actual HTML <select> |
| Explicit Wait | Synchronize with dynamic UI |
| CSS Selector | Useful for suggestion collections |
| XPath | Useful for text-based selection |
| List<WebElement> | Useful for multiple suggestions |
| Keys | Useful for keyboard navigation |
| iframe | Requires frame switching |
| Shadow DOM | Requires shadow-root access |
| Verification | Check final input value |
144. Practical Checklist
- Identify whether the dropdown is native or custom.
- Inspect the input field.
- Inspect the suggestion container.
- Identify stable attributes.
- Enter search text.
- Wait for suggestions.
- Locate the required option.
- Click the option.
- Verify the selected value.
- Handle dynamic DOM changes.
- Handle iframes if applicable.
- Handle Shadow DOM if applicable.
- Add negative test cases.
- Create reusable methods.
- Use Page Object Model for maintainable frameworks.
145. Selenium Training Resources
Selenium Training: https://www.justacademy.co/course-detail/selenium-training
Register for Course Demo: https://www.justacademy.co/register-for-course-demo
146. Final Conclusion
Auto-Suggest Dropdown automation is an important Selenium WebDriver concept because modern applications frequently use dynamically generated autocomplete components. Successful automation requires understanding the DOM, identifying stable locators, entering search text, waiting for dynamic suggestions, selecting the required option, and verifying the final value.
The most important rule is to distinguish a native HTML <select> from a custom autocomplete component. The Selenium Select class is specifically designed for <select> elements, while custom dropdowns normally require standard WebElement interactions. Proper explicit waits are also important because dynamic elements can appear or change after the initial page load.
By combining stable locators, explicit waits, dynamic element handling, keyboard interaction where appropriate, Page Object Model, reusable utility methods, and strong verification, Auto-Suggest Dropdowns can be automated reliably in Selenium WebDriver.